// pages/cut/component/cutVideo/cutVideo.js
import {getFileName} from '../../../../utils/request'
import {cutVideo} from '../../../../api/file'
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    uri: {
      type: String,
      value: ""
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    duration: 26,
    sliderValue: [10,10],
    dpr: wx.getWindowInfo().pixelRatio,
  },
  ready(){
    console.log("ready")
    console.log(this.data.uri)
    if (this.data.uri) {
      wx.showLoading({
        title: '加载中',
      })
      wx.downloadFile({
        url: this.data.uri,
        success:(res)=>{
          console.log('down===>',res)
          wx.getVideoInfo({
            src: res.tempFilePath,
            success:(r)=>{
              wx.hideLoading()
              this.setData({
                duration: r.duration
              })
            },
            fail(err){
              console.log("err====>",err)
            }
          })
        }
      })
    }
    this.videoStartCtx = wx.createVideoContext('video-start')
    this.videoEndCtx = wx.createVideoContext('video-end')
    const dpr = wx.getWindowInfo().pixelRatio
    this.setData({
      dpr: dpr
    })
    this.createSelectorQuery().select('#video-start').context(res => {
      this.videoStartCtx = res.context
    }).exec()
    this.createSelectorQuery().select('#video-end').context(res => {
      this.videoEndCtx = res.context
    }).exec()
    this.createSelectorQuery().selectAll('#start').node(res => {
      this.startCanvasCtx = res[0].node.getContext('2d')
      res[0].node.width = 300 * dpr
      res[0].node.height = 200 * dpr
    }).exec()
    this.createSelectorQuery().selectAll('#end').node(res => {
      this.endCanvasCtx = res[0].node.getContext('2d')
      res[0].node.width = 300 * dpr
      res[0].node.height = 200 * dpr
    }).exec()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    updateCanvas(start,end){
      console.log("update",start,end)
      const {dpr} = this.data
      this.videoStartCtx.seek(start)
      this.videoEndCtx.seek(end)
      setTimeout(()=>{
        const right = 300 * dpr
        const bottom = 200 * dpr
        this.startCanvasCtx.drawImage(this.videoStartCtx,0, 0, right,bottom)
        this.endCanvasCtx.drawImage(this.videoEndCtx,0, 0, right,bottom)

        this.applyGrayFilter(this.startCanvasCtx,right,bottom)
      },100)
    },

    applyGrayFilter(ctx, width, height) {
      // 获取Canvas的图像数据
      const imageData = ctx.getImageData(0, 0, width, height);
      const data = imageData.data;
  
      // 遍历每个像素，并将其转换为灰度
      for (let i = 0; i < data.length; i += 4) {
        const r = data[i];     // 红色通道
        const g = data[i + 1]; // 绿色通道
        const b = data[i + 2]; // 蓝色通道
  
        // 计算灰度值（使用标准的亮度计算公式）
        const gray = 0.299 * r + 0.587 * g + 0.114 * b;
  
        // 将RGB三个通道都设置为灰度值
        data[i] = gray;     // 红色通道
        data[i + 1] = gray; // 绿色通道
        data[i + 2] = gray; // 蓝色通道
      }
  
      // 将处理后的图像数据放回Canvas
      ctx.putImageData(imageData, 0, 0);
    },

    handleSliderChange(e) {
      this.setData({
        sliderValue:e.detail.value
      })
      const value = e.detail.value
      if(this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(()=>{
        this.updateCanvas(value[0],value[1])
        this.timer = null
      },100)
    },
    cut(){
      console.log("data===>",this)
      const {sliderValue, uri} = this.data
      if (uri == '') {
        wx.showModal({
          title: '提示',
          content: '视频不能为空'
        })
      }
      const data = {
        start: sliderValue[0],
        end: sliderValue[1],
        fileName: getFileName(uri)
      }
      wx.showLoading({
        title: '视频处理中',
      })
      cutVideo(data).then(res => {
        this.triggerEvent('updateUri',{uri:res.msg})
        wx.showToast({
          title: '操作成功',
          icon: 'success'
        })
      })
    },
    save(){
      const uri = this.data.uri
      wx.showLoading({
        title: '保存中',
      })
      wx.downloadFile({
        url: uri,
        success:(res)=>{
          uploadFile({
            filePath: res.tempFilePath
          }).then(res => {
            console.log(res)
            wx.showToast({
              title: '保存成功',
            })
          })
        }
      })
    }
  }
})